package com.eternal.base.data.ble;

import com.eternal.base.concat.HistoryInfo;
import com.eternal.base.database.entity.Log;
import com.eternal.base.protocol.CFamilialResolution;
import com.eternal.framework.utils.KLog;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class LogCParse extends BaseParse<Log> {
    private long time;
    private List<HistoryInfo> list;
    private long end;

    public void setList(List<HistoryInfo> list) {
        this.list = list;
        HistoryInfo info = list.get(list.size() - 1);
        end = info.calibrated + info.length;
    }

    @Override
    boolean checkLength() {
        return i + 6 < now.length;
    }

    @Override
    Log parse() {
        Log log = CFamilialResolution.parseLog(now, i);
        time = log.time;
        if (time >> 16 == 0xff) {
            log.time = getTime(log.id);
        }
        if (log.time > end) {
            log.id = -1;
        } else {
            log.id = (int) log.time;
        }
//        if (i == 11) {
//            long tmp = (log.time * 60 + 1577808000) * 1000;
//            DateFormat format = SimpleDateFormat.getInstance();
//            KLog.e(format.format(new Date(tmp)));
//        }
        i += 6;
        --total;
        return log;
    }

    private long getTime(int id) {
        int index, left = 0, right = list.size() - 1;
        HistoryInfo info;
        while (left + 1 != right) {
            index = (left + right) / 2;
            info = list.get(index);
            if (info.startId > id) {
                right = index;
            } else if (info.startId < id) {
                left = index;
            } else {
                return info.startId;
            }
        }
        info = list.get(right);
        if (info.startId > id) {
            info = list.get(left);
        }
        return info.calibrated + id - info.startId;
    }

    public long getLastTime() {
        return time;
    }

    @Override
    void init() {
        total = now[10] & 0xff;
        i = 11;

    }
}
